package com.shuiyun.chat.handler;

import cn.hutool.json.JSON;
import com.google.gson.Gson;
import com.shuiyun.chat.entity.message.SimpleChatMessage;
import com.shuiyun.chat.entity.vo.UserVO;
import com.shuiyun.chat.enums.ChatSessionKey;
import com.shuiyun.chat.service.UserService;
import com.shuiyun.chat.utils.RedisUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @program: chatServer
 * @description: 简单消息处理
 * @author: shuiyun
 * @create: 2021-05-13 00:31
 **/
@Service
@ChannelHandler.Sharable
@Slf4j
public class SimpleChatMessageHandler extends SimpleChannelInboundHandler<SimpleChatMessage> {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;


    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, SimpleChatMessage simpleChatMessage) throws Exception {
        Channel channel = channelHandlerContext.channel();
        UserVO user = userService.getUserByChannel(channel);
        simpleChatMessage.setSrc(user.getNickName());
        Channel toChannel = userService.getChannelByUserName(simpleChatMessage.getTo());
        if (null == toChannel){
            // 如果对方不在线 则缓存该消息 等待发送
            redisUtil.rightPush(ChatSessionKey.simpleChat.getKey()+simpleChatMessage.getTo(), new Gson().toJson(simpleChatMessage));
            return;
        }
        toChannel.writeAndFlush(simpleChatMessage);
    }
}
